﻿using System.Linq;
using UnityEngine;


/// <summary>
/// 
/// </summary>
public class RInputModuleItem : MonoBehaviour
{
    [Tooltip("实例管理")] public KeyItem[] keyConfigItems;
    [Tooltip("存储管理")] RInputModuleStorage rIStorage;



    public void Init()
    {
        keyConfigItems = transform.GetComponentsInChildren<KeyItem>(true);

        var maps = RInputManager.Instance.rIStorage?.Collection?.mappings;

        if (maps == null) return;

        foreach (var map in maps)
        {
            var item = keyConfigItems.FirstOrDefault(i => i.mapping.actionName == map.actionName);
            if (item == null)
            {
                Debug.LogWarning($"{map.actionName} 游戏内缺失实例对象");
                continue;
            }
            item.Init(map);
        }
    }


    public void ReBind(RInputModuleStorage rIStorage)
    {
        this.UnBind();
        this.Bind(rIStorage);
    }
    public void Bind(RInputModuleStorage rIStorage)
    {
        this.rIStorage = rIStorage;
        this.rIStorage.OnStorageLoaded += OnItemInit;
    }
    public void UnBind()
    {
        if (this.rIStorage != null)
        {
            this.rIStorage.OnStorageLoaded -= OnItemInit;
            this.rIStorage = null;
        }
    }


    private void OnItemInit(DataKeyCollection collection)
    {
        foreach (var mapping in collection.mappings)
        {
            var item = keyConfigItems.FirstOrDefault(i => i.mapping.actionName == mapping.actionName);
            if (item == null)
            {
                Debug.LogWarning($"{mapping.actionName} 游戏内缺失实例对象");
                continue;
            }
            item.Init(mapping);
        }
    }
}